package com.bnyy.medicalHousekeeper.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bnyy.common.Constant;
import com.bnyy.gbp.permission.PermissionHelper;
import com.bnyy.medicalHousekeeper.BuildConfig;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.App;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.fragment.IndexFragment;
import com.bnyy.medicalHousekeeper.fragment.MineFragment;
import com.bnyy.medicalHousekeeper.moudle.message.MessageManager;
import com.bnyy.medicalHousekeeper.moudle.message.MessageService;
import com.bnyy.medicalHousekeeper.moudle.message.fragment.ChatsFragment;
import com.bnyy.medicalHousekeeper.moudle.message.fragment.MessageHomePageFragment;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.List;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2023/2/1
 **/
public class MainActivity extends BaseActivityImpl {
    @BindView(R.id.fl_container)
    FrameLayout flContainer;
    @BindView(R.id.rb_index)
    RadioButton rbIndex;
    @BindView(R.id.rb_message)
    RadioButton rbMessage;
    @BindView(R.id.rb_mine)
    RadioButton rbMine;
    @BindView(R.id.rl_root)
    LinearLayout rlRoot;
    @BindView(R.id.tv_unread_count)
    TextView tvUnreadCount;

    private IndexFragment indexFragment;
    private MessageHomePageFragment messageHomePageFragment;
    private MineFragment mineFragment;

    private ServiceConnection messageServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bindService(new Intent(mContext, MessageService.class), this, BIND_AUTO_CREATE);
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public String getTitleStr() {
        return null;
    }

    @Override
    public boolean unuseRefreshLayout() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PermissionHelper.getInstance().requestPermission(new PermissionHelper.RequestPermission() {
            @Override
            public String[] permissions() {
                return new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
            }

            @Override
            public void granted(HashSet<String> granted) {
                MessageManager.init(mContext);
            }

            @Override
            public void denied(HashSet<String> denied) {

            }
        });
        bindService(new Intent(mContext, MessageService.class), messageServiceConnection, BIND_AUTO_CREATE);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rbIndex.setChecked(false);
                rbMessage.setChecked(false);
                rbMine.setChecked(false);

                RadioButton rb = (RadioButton) v;
                rb.setChecked(true);

                Fragment target = null;
                if (App.getUser() == null) {
                    BaseActivityImpl.show(mContext, LoginActivity.class);
                    finish();
                    return;
                }

                switch (v.getId()) {
                    case R.id.rb_index:
                        if (indexFragment == null) {
                            indexFragment = new IndexFragment();
                        }
                        target = indexFragment;
                        break;
                    case R.id.rb_message:
                        if (messageHomePageFragment == null) {
                            messageHomePageFragment = new MessageHomePageFragment();
                        }
                        target = messageHomePageFragment;
                        break;
                    case R.id.rb_mine:
                        if (mineFragment == null) {
                            mineFragment = new MineFragment();
                        }
                        target = mineFragment;
                        break;
                }
                switchFragment(target);
            }
        };

        rbIndex.setOnClickListener(onClickListener);
        rbMessage.setOnClickListener(onClickListener);
        rbMine.setOnClickListener(onClickListener);

        rbIndex.performClick();

        regToWx();
    }

    private void regToWx() {
        Log.e("MD5", getSingInfo(mContext, BuildConfig.APPLICATION_ID, MD5));
        Log.e("SHA1", getSingInfo(mContext, BuildConfig.APPLICATION_ID, SHA1));
        Log.e("SHA256", getSingInfo(mContext, BuildConfig.APPLICATION_ID, SHA256));

        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.WX.APP_ID, true);
        // 将应用的appId注册到微信
        api.registerApp(Constant.WX.APP_ID);

        // 建议动态监听微信启动广播进行注册到微信
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                IWXAPI api = WXAPIFactory.createWXAPI(context, Constant.WX.APP_ID, true);
                // 将该app注册到微信
                api.registerApp(Constant.WX.APP_ID);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
    }

    static String TAG = "AppSigning";

    public final static String MD5 = "MD5";
    public final static String SHA1 = "SHA1";
    public final static String SHA256 = "SHA256";

    /**
     * 返回一个签名的对应类型的字符串
     *
     * @param context
     * @param packageName
     * @param type
     * @return
     */
    public static String getSingInfo(Context context, String packageName, String type) {
        String tmp = "error!";
        try {
            Signature[] signs = getSignatures(context, packageName);
            Signature sig = signs[0];

            if (MD5.equals(type)) {
                tmp = getSignatureString(sig, MD5);
            } else if (SHA1.equals(type)) {
                tmp = getSignatureString(sig, SHA1);
            } else if (SHA256.equals(type)) {
                tmp = getSignatureString(sig, SHA256);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tmp;
    }

    /**
     * 返回对应包的签名信息
     *
     * @param context
     * @param packageName
     * @return
     */
    public static Signature[] getSignatures(Context context, String packageName) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            return packageInfo.signatures;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取相应的类型的字符串（把签名的byte[]信息转换成16进制）
     *
     * @param sig
     * @param type
     * @return
     */
    public static String getSignatureString(Signature sig, String type) {
        byte[] hexBytes = sig.toByteArray();
        String fingerprint = "error!";
        try {
            StringBuffer buffer = new StringBuffer();
            MessageDigest digest = MessageDigest.getInstance(type);
            if (digest != null) {
                digest.reset();
                digest.update(hexBytes);
                byte[] byteArray = digest.digest();
                for (int i = 0; i < byteArray.length; i++) {
                    if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                        buffer.append("0").append(Integer.toHexString(0xFF & byteArray[i])); //补0，转换成16进制
                    } else {
                        buffer.append(Integer.toHexString(0xFF & byteArray[i]));//转换成16进制
                    }
                }
//                fingerprint = buffer.toString().toUpperCase(); //转换成大写
                //*********转换成小写**********//
                fingerprint = buffer.toString().toLowerCase();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return fingerprint;
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUnreadCount();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (messageServiceConnection != null) {
            unbindService(messageServiceConnection);
        }
    }

    private void setUnreadCount() {
        int totalUnreadCount = MessageManager.getTotalUnreadCount();
        tvUnreadCount.setTag(totalUnreadCount);
        if (totalUnreadCount > 0) {
            tvUnreadCount.setVisibility(View.VISIBLE);
            if (totalUnreadCount > 99) {
                tvUnreadCount.setText("99+");
            } else {
                tvUnreadCount.setText(totalUnreadCount + "");
            }
        } else {
            tvUnreadCount.setVisibility(View.INVISIBLE);
        }
    }

//    @OnClick({R.id.rb_index, R.id.rb_message, R.id.rb_mine})
//    public void onViewClicked(View view) {
//        Fragment target = null;
//        if (App.getUser() == null) {
//            BaseActivityImpl.show(mContext, LoginActivity.class);
//            finish();
//            return;
//        }
//
//        switch (view.getId()) {
//            case R.id.rb_index:
//                if (indexFragment == null) {
//                    indexFragment = new IndexFragment();
//                }
//                target = indexFragment;
//                break;
//            case R.id.rb_message:
//                if (chatsFragment == null) {
//                    chatsFragment = new ChatsFragment();
//                }
//                target = chatsFragment;
//                break;
//            case R.id.rb_mine:
//                if (mineFragment == null) {
//                    mineFragment = new MineFragment();
//                }
//                target = mineFragment;
//                break;
//        }
//        switchFragment(target);
//    }

    private void switchFragment(Fragment fragment) {
        if (fragment != null) {
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            if (fragment.isAdded()) {
                if (fragment.isHidden()) {
                    List<Fragment> fragments = manager.getFragments();
                    for (Fragment f : fragments) {
                        if (!f.isHidden()) {
                            transaction.hide(f);
                        }
                    }
                    transaction.show(fragment);
                }
            } else {
                List<Fragment> fragments = manager.getFragments();
                for (Fragment f : fragments) {
                    if (!f.isHidden()) {
                        transaction.hide(f);
                    }
                }
                transaction.add(flContainer.getId(), fragment);
            }
//            if (fragment.isAdded()) {
//                transaction.show(fragment);
//            } else {
//                transaction.add(R.id.fm_container, fragment);
//            }
            transaction.commitNowAllowingStateLoss();
        }
    }
}

































